package com.gzdh.tang.ali.rule;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gzdh.tang.comm.constant.SpringContextUtils;
import com.gzdh.tang.comm.handler.IPayRuleHandler;
import com.gzdh.tang.comm.vo.Result;
import com.gzdh.tang.modu.entity.*;
import com.gzdh.tang.modu.model.HexiaoOrderModel;
import com.gzdh.tang.modu.service.*;
import com.gzdh.tang.warehouse.service.DeviceService;
import com.gzdh.tang.warehouse.service.InStockService;
import lombok.extern.slf4j.Slf4j;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 文化局的实现规则
 */
@Slf4j
public class AliWenHuaRule implements IPayRuleHandler {


    FkService fkService;

    GsService gsService;

    MacMainpSbruanService macMainpSbruanService;

    MacMainpSbruanDinnerService macMainpSbruanDinnerService;

    MacMainpSbruanKlService macMainpSbruanKlService;

    ReserveService reserveService;

    TangDeviceService tangDeviceService;

    DeviceService deviceService;

    InStockService inStockService;


    MacMainpSbruanKlDinnerService macMainpSbruanKlDinnerService;

    MacMainpSbruanKlButieService macMainpSbruanKlButieService;

    public AliWenHuaRule() {
        fkService = (FkService) SpringContextUtils.getBean("fkServiceImpl");
        gsService = (GsService) SpringContextUtils.getBean("gsService");
        macMainpSbruanService = (MacMainpSbruanService) SpringContextUtils.getBean("macMainpSbruanService");
        macMainpSbruanDinnerService = (MacMainpSbruanDinnerService) SpringContextUtils.getBean("macMainpSbruanDinnerService");
        macMainpSbruanKlService = (MacMainpSbruanKlService) SpringContextUtils.getBean("macMainpSbruanKlService");
        reserveService = (ReserveService) SpringContextUtils.getBean("reserveService");
        tangDeviceService = (TangDeviceService) SpringContextUtils.getBean("tangDeviceServiceImpl");
        deviceService = (DeviceService) SpringContextUtils.getBean("deviceServiceImpl");
        inStockService = (InStockService) SpringContextUtils.getBean("inStockService");
        macMainpSbruanKlDinnerService = (MacMainpSbruanKlDinnerService) SpringContextUtils.getBean("macMainpSbruanKlPriceService");
        macMainpSbruanKlButieService = (MacMainpSbruanKlButieService) SpringContextUtils.getBean("macMainpSbruanKlButieService");
    }

    @Override
    public JSONObject toCardPay(JSONObject params) throws RuntimeException {
        String cardsn = params.getString("cardsn");
        String deviceId = params.getString("deviceId");

        HexiaoOrderModel hexiaoOrderModel = new HexiaoOrderModel();
        String orders = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        Fk fk = fkService.getOne(new QueryWrapper<Fk>().lambda().eq(Fk::getCardsn, cardsn));
        if (fk == null) {
            throw new RuntimeException("查无此人");
        }
        MacMainpSbruan macMainpSbruan = macMainpSbruanService.getOne(new QueryWrapper<MacMainpSbruan>().lambda()
                .eq(MacMainpSbruan::getMac, deviceId));
        String dinenr = macMainpSbruanService.getDinnerByDeviceId(deviceId, new Date());
        if (StringUtils.isEmpty(dinenr)) {
            throw new RuntimeException("餐次获取失败");
        }
        //获取固定消费金额
        MacMainpSbruanKlDinner macMainpSbruanKlDinner = macMainpSbruanKlDinnerService
                .getOne(new QueryWrapper<MacMainpSbruanKlDinner>().lambda().eq(MacMainpSbruanKlDinner::getDinner, dinenr).eq(MacMainpSbruanKlDinner::getKl, fk.getKl()));
        if (macMainpSbruanKlDinner == null) {
            throw new RuntimeException("固定核销获取失败");
        }
        int count = gsService.count(new QueryWrapper<Gs>().lambda().eq(Gs::getKh, fk.getKh()).eq(Gs::getCardno, fk.getCardno()));
        if (count > 0) {
            throw new RuntimeException("此卡已挂失,请回收");
        }
        List<MacMainpSbruanKl> macMainpSbruanKlList = macMainpSbruanKlService.list(new QueryWrapper<MacMainpSbruanKl>().lambda()
                .eq(MacMainpSbruanKl::getDeviceId, macMainpSbruan.getId()));
        if (!judeKl(macMainpSbruanKlList, fk.getKl())) {
            throw new RuntimeException("不支持此卡类");
        }
        int counts = reserveService.count(new QueryWrapper<Reserve>().lambda().eq(Reserve::getDcrq,
                        new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()))
                .eq(Reserve::getDinner, dinenr).eq(Reserve::getCardno, fk.getCardno()));
        if (counts > 0) {
            throw new RuntimeException("当前用户在当前餐次已消费");
        }

        Map<String, String> priceMap = macMainpSbruanKlButieService.getPayPrice(fk.getKl(), dinenr, macMainpSbruanKlDinner.getPrice());
        orders += macMainpSbruan.getPos();
        hexiaoOrderModel.setAccountPrice(priceMap.get("accountPrice"));
        hexiaoOrderModel.setAmountPrice(priceMap.get("amount"));
        hexiaoOrderModel.setYouhuiPrice(priceMap.get("youhuiPrice"));
        BigDecimal accountPrice = new BigDecimal(priceMap.get("accountPrice"));
        BigDecimal youhuiPrice = new BigDecimal(priceMap.get("youhuiPrice"));
        macMainpSbruan.setDinner(dinenr);
        if (new BigDecimal(fk.getKye()).compareTo(accountPrice) < 0) {
            throw new RuntimeException("余额不足");
        }
        if (youhuiPrice.compareTo(new BigDecimal(0)) == 1) {
            insertReserve("1", deviceId, "ICZF" + orders, fk.getCardsn(), youhuiPrice, "0", fk, macMainpSbruan);
        }
        insertReserve("0", deviceId, "ICZF" + orders, fk.getCardsn(), accountPrice, "0", fk, macMainpSbruan);
        return null;
    }

    @Override
    public JSONObject toCashPay(JSONObject params) throws RuntimeException {
        return null;
    }

    @Override
    public JSONObject toQrPay(JSONObject params) throws RuntimeException {
        return null;
    }

    @Override
    public JSONObject toFacePay(JSONObject params) throws RuntimeException {
        return null;
    }


    private boolean judeKl(List<MacMainpSbruanKl> macMainpSbruanKlList, String kl) {
        for (MacMainpSbruanKl goo : macMainpSbruanKlList) {
            if (goo.getKl().equals(kl.trim())) {
                return true;
            }
        }
        return false;
    }


    private boolean insertReserve(String sc, String rgTermSN, String reqSeqNo, String cardsn, BigDecimal price, String dateStr,
                                  Fk fk, MacMainpSbruan macMainpSbruan) throws RuntimeException {
        BigDecimal xfPrice = price;
        BigDecimal yePrice = new BigDecimal(0);
        BigDecimal kye = new BigDecimal(fk.getKye());
        BigDecimal btye = new BigDecimal(fk.getBtye());
        Date date = new Date();
        if ("0".equals(dateStr)) {
            date = new Date();
        } else {
            try {
                date = new SimpleDateFormat("yyyyMMddHHmmss").parse(dateStr);
            } catch (Exception e) {
                throw new RuntimeException("时间异常");
            }
        }
        Reserve reserve = new Reserve();
        reserve.setCardno(fk.getCardno());
        reserve.setZl(macMainpSbruan.getZl());
        reserve.setBqh(fk.getBqh());
        reserve.setKsh(fk.getKsh());
        reserve.setBed("0");
        reserve.setPosnum(macMainpSbruan.getPos());
        reserve.setDinner(macMainpSbruan.getDinner());
        reserve.setCode(macMainpSbruan.getCode());
        reserve.setSl(1);
        reserve.setJe(price.toPlainString());
        try {
            reserve.setYe(yePrice.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString());
        } catch (Exception e) {
            log.error("余额错误");
            reserve.setYe("0");
        }
        reserve.setKl(fk.getKl());
        reserve.setSc(sc);
        reserve.setLsh2(String.valueOf(reqSeqNo));
        reserve.setCzrq(date);
        reserve.setDcrq(new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(new Date()));
        reserve.setHname("现金菜");
        reserve.setSddz(rgTermSN);
        reserve.setCs(0);
        reserve.setOpenid(cardsn);
        reserve.setKehu(fk.getName());
        reserve.setZfserialnumber(String.valueOf(reqSeqNo));
        reserve.setAddr(macMainpSbruan.getAddr());
        reserveService.save(reserve);
        return true;
    }

}
